package com.gxa.sso.controller;

import com.gxa.sso.entity.User;
import com.gxa.sso.exception.BusinessException;
import com.gxa.sso.service.UserService;
import com.gxa.sso.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @PostMapping("/login")
    public JsonResult login(@RequestParam String phone,@RequestParam String code) throws BusinessException {
        if(!phone.matches("^[1](([3][0-9])|([4][5,7,9])|([5][0-9])|([6][6])|([7][3,5,6,7,8])|([8][0-9])|([9][8,9]))[0-9]{8}$")){
            throw new BusinessException("手机号码格式不合法");
        }
        Map<String, String> login = userService.login(phone, code);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(login);

        return jsonResult;
    }


    @PostMapping("/validateToken")
    public JsonResult validateToken(@RequestParam String token) throws BusinessException {
        User user = userService.validateToken(token);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(user);
        return jsonResult;
    }
}
